#Region " Imports "

Imports System.Configuration
Imports System.Web.Configuration
Imports System.Net.Configuration
Imports BlazeApps.Library.Messaging
Imports System.Data

#End Region

Partial Class Usercontrols_Messaging_MessageSystem
    Inherits UserControlBase

#Region " Enums, Memebers and Properties "

    Private DataPageLocal As New PagedDataSource

    Public Property sortCriteria() As String
        Get
            Return CStr(ViewState("sortCriteria"))
        End Get

        Set(ByVal Value As String)
            ViewState("sortCriteria") = Value
        End Set
    End Property

    Public Property sortDir() As String
        Get
            Return CStr(ViewState("sortDir"))
        End Get

        Set(ByVal Value As String)
            ViewState("sortDir") = Value
        End Set
    End Property

    Public Property ListType() As Integer
        Get
            Return GetIntegerFromVS("MessageListType")
        End Get

        Set(ByVal Value As Integer)
            ViewState("MessageListType") = Value
        End Set
    End Property

    Private Property MessageGuid() As Guid
        Get
            Return GetGuidFromVS("MessageID")
        End Get
        Set(ByVal value As Guid)
            ViewState("MessageID") = value
        End Set
    End Property

    Public Property IsLoadedAsOption() As Boolean
        Get
            Return GetBooleanFromVS("IsLoadedAsOption")
        End Get
        Set(ByVal value As Boolean)
            ViewState.Add("IsLoadedAsOption", value)
        End Set
	End Property

#End Region

#Region " Page Events "

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Me.MessageLabel = Me.uxMessagesLabel
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not IsLoadedAsOption Then
            SetPageTitle(Resources.Resource.MessageSystem)
        End If

        If IsUserAuthenticated = True Then

            If Me.Page.IsPostBack = False Then

                'Set Default Sort Order and Direction
                Me.sortCriteria = "createdate"
                Me.sortDir = "asc"

                LoadPage()

                Me.uxMessageSystemTitleLabel.Text = Resources.Resource.PrivateMessage

                If GetStringFromQueryString("userid") <> String.Empty Then
                    Me.uxPrivateMessageToTextBox.Text = GetStringFromQueryString("userid").Trim
                End If

            End If

            ConfigBaseNavCtrls()

            If Me.Page.IsPostBack = False Then
                ListType = MessageListType.Inbox
                Me.uxMessageSystemTitleLabel.Text = Resources.Resource.Inbox
                BindDataItems()
            End If

        End If

        Me.uxMemberPanel.Visible = ShowControls(SecurityMask.Member, True)

    End Sub

#End Region

#Region " Save Data "

    Private Sub SendMessage()
        Dim ToList() As String
        Dim Name As Object

        ToList = Split(Me.uxPrivateMessageToTextBox.Text.ToString.Trim, ",")

        For Each Name In ToList
            Dim Message As PrivateMessage = PrivateMessage.NewPrivateMessage
            Dim ToUserID As New Guid(Membership.GetUser(Name.ToString).ProviderUserKey.ToString)

            SendPrivateMessage(ToUserID, CurrentUserID, Me.uxPrivateMessageSubjectTextBox.Text.Trim, Me.uxMessageTextBox.Text.Trim)
        Next

        ClearTextBoxes()

    End Sub

#End Region

#Region " Load Data "

    Private Sub LoadPage()
        LoadPageSize(Me.uxPageSizeDropDownList)
    End Sub

    Private Sub LoadReplyScreen()

        Dim Message As PrivateMessage = PrivateMessage.GetPrivateMessage(MessageGuid)

        Me.uxPrivateMessageSubjectTextBox.Text = String.Format("{0} {1}", Resources.Resource.RE, Message.subject)
        Me.uxMessageTextBox.Text = String.Format("<br />----------------- {0} -------------------<br /> {1}", Resources.Resource.PreviousMessage, Message.body)

        Me.uxNewMessageModalPopupExtender.Show()

    End Sub

    Protected Sub LoadMessage(ByVal sender As Object, ByVal e As CommandEventArgs)
        MessageGuid = ConvertToGuid(e.CommandArgument)

        Dim Message As PrivateMessage = PrivateMessage.GetPrivateMessage(MessageGuid)

        Me.uxPrivateMessageFromDisplayLabel.Text = UserName(Message.fromuserid.ToString.Trim)
        Me.uxPrivateMessageSubjectDisplayLabel.Text = Message.subject
		Me.uxPrivateMessageDisplayLabel.Text = SetHTMLReturn(Message.body)

		SetMultiViewIndex(MessageViewIndex.Message)

    End Sub

    Private Sub RebindData(ByVal ListTypeSelection As MessageListType)
        ListType = ListTypeSelection
        Me.PageNumber = 0
        BindDataItems()
    End Sub

    Public Overloads Overrides Sub BindDataItems()
        Dim SentItems As New SentItems
        Dim InboxList As New Inbox
        Dim DT As New DataTable
        Dim DV As New DataView

        If ListType = MessageListType.SentItems Then
            DT = SentItems.GetSentItemsList(Membership.GetUser(CurrentUser).ProviderUserKey)
        End If

        If ListType = MessageListType.Inbox Then
            DT = InboxList.GetInboxList(Membership.GetUser(CurrentUser).ProviderUserKey)
        End If

        Me.RecordCount = DT.Rows.Count

        DV.Table = DT

        DV.Sort = Me.sortCriteria & " " & Me.sortDir

        Me.DataPage.DataSource = DV
        Me.DataPage.AllowPaging = True
        Me.DataPage.PageSize = CType(Me.uxPageSizeDropDownList.SelectedValue.ToString, Integer)
        Me.DataPage.CurrentPageIndex = Me.PageNumber

        CreatePagingLinks()

        With Me.uxResultsGridView
            .DataSource = Me.DataPage
            .DataBind()
        End With

    End Sub

#End Region

#Region " Form Controls Events "

    Protected Sub uxSubmitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uxSubmitButton.Click
        SendMessage()

        RebindData(MessageListType.SentItems)
        SetMultiViewIndex(MessageViewIndex.ListItems)

        Me.uxNewMessageModalPopupExtender.Hide()
    End Sub

    Protected Sub uxFindUserButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uxFindUserButton.Click
        ScriptManager.RegisterStartupScript(uxFindUserButton, Me.GetType(), "memberlist", "fPopUpWin(' " & String.Format("{0}.aspx?pid=cp_memberlist&popup=1&form={1}&control={2}", AppPage, Me.Page.Form.Name.ToString.Trim, Me.uxPrivateMessageToTextBox.ClientID) & "','memberlist',1,1,1, 790, 500, 0);", True)
    End Sub

    Protected Sub uxReplyImageButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles uxReplyImageButton.Click
        LoadReplyScreen()
        SetMultiViewIndex(MessageViewIndex.ListItems)
        Me.uxMessageSystemTitleLabel.Text = Resources.Resource.Inbox
    End Sub

    Protected Sub uxDeleteMessageImagebutton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles uxDeleteMessageImagebutton.Click
        If Not (MessageGuid = Guid.Empty) Then
            'Deletes currently viewed message
            PrivateMessage.DeletePrivateMessage(MessageGuid)

            ClearLabels()
        End If
    End Sub

    Protected Sub uxDeleteImageButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles uxDeleteImageButton.Click
        Dim AttachmentList As New StringBuilder
        Dim iI As Integer

        If Not (MessageGuid = Guid.Empty) Then
            'Deletes currently viewed message
            PrivateMessage.DeletePrivateMessage(MessageGuid)

            ClearLabels()
        End If

        While iI < Me.uxResultsGridView.Rows.Count
            Dim Row As GridViewRow = Me.uxResultsGridView.Rows(iI)
            Dim ID As New Guid(CType(Row.FindControl("uxMessageIDLable"), Label).Text.ToString.Trim)

            Dim Checked As Boolean = CType(Row.FindControl("uxSelectCheckBox"), CheckBox).Checked

            If Checked Then
                PrivateMessage.DeletePrivateMessage(ID)
            End If

            System.Math.Min(System.Threading.Interlocked.Increment(iI), iI - 1)

        End While

        RebindData(MessageListType.Inbox)
        Me.uxMessageSystemTitleLabel.Text = Resources.Resource.Inbox
    End Sub

    Protected Sub uxResultsGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles uxResultsGridView.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim IB As ImageButton = CType(e.Row.FindControl("uxViewMessageLinkButton"), ImageButton)
            Dim Viewed As Boolean

            Viewed = DataBinder.Eval(e.Row.DataItem, "isviewed")

            If Viewed = True Then
                IB.ImageUrl = "~/App_Themes/" & Page.Theme.ToString & "/images/icons/emailviewed.gif"
            Else
                IB.ImageUrl = "~/App_Themes/" & Page.Theme.ToString & "/images/icons/emailnew.gif"
            End If

        End If
    End Sub

    Protected Sub uxResultsGridView_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles uxResultsGridView.Sorting
        'Get the Sort by Value from the Sortexpression field on the column
        If Me.sortCriteria = e.SortExpression Then
            If Me.sortDir = "desc" Then
                Me.sortDir = "asc"
            Else
                Me.sortDir = "desc"
            End If
        End If

        ' Assign the column clicked to the sortCriteria property
        Me.sortCriteria = e.SortExpression

        'Calls the function to rebuild the datagrid view, with the new sort order
        BindDataItems()
    End Sub

    Protected Sub uxSentItemsImageButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles uxSentItemsImageButton.Click
        RebindData(MessageListType.SentItems)
        SetMultiViewIndex(MessageViewIndex.ListItems)
        Me.uxMessageSystemTitleLabel.Text = Resources.Resource.SentItems.ToString
    End Sub

    Protected Sub uxInboxImageButton_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles uxInboxImageButton.Click
        RebindData(MessageListType.Inbox)
        SetMultiViewIndex(MessageViewIndex.ListItems)
		Me.uxMessageSystemTitleLabel.Text = Resources.Resource.Inbox.ToString
    End Sub

#End Region

#Region " Helpers and Methods "

    Private Sub ClearTextBoxes()
        Me.uxMessageTextBox.Text = String.Empty
        Me.uxPrivateMessageSubjectTextBox.Text = String.Empty
        Me.uxPrivateMessageToTextBox.Text = String.Empty
    End Sub

    Private Sub ClearLabels()
        Me.uxPrivateMessageFromDisplayLabel.Text = String.Empty
        Me.uxPrivateMessageSubjectDisplayLabel.Text = String.Empty
        Me.uxPrivateMessageDisplayLabel.Text = String.Empty
    End Sub

    Private Sub SetMultiViewIndex(ByVal Index As MessageViewIndex)
        Me.uxMessageSystemMultiView.ActiveViewIndex = Index
    End Sub

    Private Sub ConfigBaseNavCtrls()

        Me.PagingTopPanel = Me.uxPagingTopPanel
        Me.PagingBottomPanel = Me.uxPagingBottomPanel

        Me.RepeaterTop = Me.uxPagesTopRepeater
        Me.RepeaterBottom = Me.uxPagesBottomRepeater

        Me.NextTopLinkButton = Me.uxTopNextLinkButton
        Me.PreviousTopLinkButton = Me.uxTopPrevLinkButton
        Me.NextBottomLinkButton = Me.uxBottomNextLinkButton
        Me.PreviousBottomLinkButton = Me.uxBottomPrevLinkButton

        Me.DataPage = DataPageLocal
        Me.PageSize = CType(Me.uxPageSizeDropDownList.SelectedValue.ToString, Integer)
        Me.PagesToDisplay = 10

        Me.ItemsPerPageDropDown = Me.uxPageSizeDropDownList
        Me.ItemsPerPageLabel = Me.uxItemsPerPageLabel
        Me.PagerInfoLabel = Me.uxPagerInfoLabel

        AddHandler Me.RepeaterTop.ItemCommand, AddressOf PagingRepeater_ItemCommand
        AddHandler Me.RepeaterBottom.ItemCommand, AddressOf PagingRepeater_ItemCommand

    End Sub

#End Region

End Class
